<?php

namespace App\Http\Controllers;

use App\Models\Buy;
use Illuminate\Http\Request;

class CallbackController extends Controller
{
  public function indexForAdmin(Request $request)
  {
    $page = Buy::select('id', 'seller_id', 'transaction_id', 'callback_num', 'callback_ok', 'state')
      ->with('seller:id,username,notify_url')
      ->when($request->has('transaction_id'), function ($q) {
        $q->where('transaction_id', request('transaction_id'));
      })
      ->when($request->has('id'), function ($q) {
        $q->where('id', request('id'));
      })
      ->when($request->has('seller_username'), function ($q) {
        $q->whereHas('seller', function ($q) {
          $q->where('username', request('seller_username'));
        });
      })
      ->whereNotNull('transaction_id')
      ->whereIn('state', ['unfreeze', 'frozen', 'fail'])
      ->latest()
      ->page();

    return success($page);
  }

  public function send(Request $request)
  {
    $buy = Buy::findOrFail($request->id);

    $buy->callback();
    return success('ok');
  }
}
